package com.jackeysun.app_common

import android.R.attr
import android.annotation.SuppressLint
import android.content.res.Resources
import android.graphics.*
import android.graphics.drawable.Drawable
import android.graphics.pdf.PdfRenderer
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.jackeysun.app_common.databinding.ActivityMain5Binding
import com.jackeysun.app_common.databinding.ItemPdfBinding
import com.jackeysun.common.IData
import java.io.IOException
import android.widget.LinearLayout
import com.bumptech.glide.request.target.DrawableImageViewTarget
import android.R.attr.resource
import android.graphics.drawable.BitmapDrawable
import com.bumptech.glide.load.engine.DiskCacheStrategy
import android.graphics.Bitmap
import android.os.ParcelFileDescriptor
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.request.target.Target
import com.jackeysun.util.middleToast
import com.jackeysun.util.scale
import com.jackeysun.util.screenWidth
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import top.zibin.luban.Luban
import java.io.ByteArrayOutputStream
import java.io.File


class MainActivity5 : AppCompatActivity() {

    private var pages = mutableListOf<PageBean>()
//    private var bitmaps = mutableListOf<Bitmap>()

    @SuppressLint("WrongThread")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val mBinding = ActivityMain5Binding.inflate(layoutInflater)
        setContentView(mBinding.root)

        lifecycleScope.launch {
            try {
                val res = appendBitmap(readPdf())
                Log.d("TAG", "onCreate: ${res?.byteCount}")
                if (res != null) {
                    val bit = res scale (screenWidth().toFloat() / res.width)
                    Log.d("TAG", "onCreate: ${bit.byteCount}")
                    mBinding.iv.setImageBitmap(bit)
                }
            } catch (e: Exception) {
//                e.printStackTrace()
                "文件解析错误".middleToast()
            }
        }
//        val requestOptions = RequestOptions().placeholder(0).dontAnimate().error(0)

//        val width = Resources.getSystem().displayMetrics.widthPixels

//        if (res != null){
//            val imageHeight = res.height * 1.00
//            val imageWidth = res.width * 1.00
//            val imageTotalHeight = width * (imageHeight / imageWidth)
//            mBinding.iv.setHeight {
//                it.height = imageTotalHeight.toInt()
//            }
//        }
//        val drawable = BitmapDrawable(mBinding.iv.resources, res)
//        val requestOptions = RequestOptions().centerCrop()
//            .diskCacheStrategy(DiskCacheStrategy.ALL)
//            .error(drawable)//放在出错位置
//            .placeholder(drawable)//放在占位符位置
//        Glide.with(this)
//            .setDefaultRequestOptions(requestOptions)
//            .load("https://${System.currentTimeMillis()}")//随便给个不可用的url
//            .into(mBinding.iv)

//
////        val baos = ByteArrayOutputStream()
//        val bitmap: Bitmap = res?:return
////        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
//        val bytes: ByteArray = baos.toByteArray()
//        Glide.with(this).load(bytes).centerCrop().into<Target<Drawable>>(holder.imageView)


//        Glide.with(this).asBitmap().load(res).into(mBinding.iv)

//        Glide.with(this)
//            .load(res)
////            .apply(requestOptions)
//            .into(object:DrawableImageViewTarget(mBinding.iv) {
//                override fun onResourceReady(
//                    resource: Drawable,
//                    transition: Transition<in Drawable>?
//                ) {
//                    super.onResourceReady(resource, transition)
////                    val width: Float = resource.getIntrinsicWidth().toFloat()
////                    val height: Float = resource.getIntrinsicHeight().toFloat()
////                    var ivWidth: Float = mBinding.iv.getWidth().toFloat()
////                    if (ivWidth == 0f) {
////                        ivWidth = mBinding.iv.getResources().getDisplayMetrics().widthPixels.toFloat()
////                    }
////                    val ivHeight = (height / width * ivWidth).toInt()
////                    val lp: ViewGroup.LayoutParams = mBinding.iv.getLayoutParams()
////                    lp.height = ivHeight
////                    mBinding.iv.setLayoutParams(lp)
//                }
//            })


//        val adapter = AbsAdapter<PageBean>()
//        adapter.addLayout(0, R.layout.item_pdf)
//        adapter.data = pages
//        mBinding.rv.adapter = adapter
//        mBinding.rv.layoutManager = LinearLayoutManager(this)


    }

    fun View.setHeight(block: (lp: ViewGroup.LayoutParams) -> Unit) {
        post {
            val lp = this.layoutParams
//        lp.height = height
            block(lp)
            this.layoutParams = lp
        }
    }

//    private fun readPdf() {
//        // create a new renderer
//        var renderer: PdfRenderer? = null
//        try {
//            val mFileDescriptor = assets.openFd("sample.pdf").parcelFileDescriptor
//            renderer = PdfRenderer(mFileDescriptor)
//
//            // let us just render all pages
//            val pageCount = renderer.pageCount
//
//            for (i in 0 until pageCount) {
//
////                val page: PdfRenderer.Page = renderer.openPage(i)
////                val width = page.width * 2
////                val height = page.height * 2
////                val mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
////                val canvas = Canvas(mBitmap)
////                canvas.drawColor(Color.WHITE)
////                val paint = Paint()
////                paint.color = Color.BLACK
////                canvas.drawBitmap(mBitmap, 0f, 0f, paint)
////                val r = Rect(0, 0, width, height)
////                val transform = Matrix()
////                transform.setScale(2f, 2f)
////                page.render(mBitmap, r, transform, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
////                pages.add(PageBean(mBitmap, i, pageCount))
////                bitmaps.add(mBitmap)
////                page.close()
//
//                val page: PdfRenderer.Page = renderer.openPage(i)
//                val mBitmap = Bitmap.createBitmap(page.width, page.height, Bitmap.Config.ARGB_8888)
//                // say we render for showing on the screen
//                page.render(mBitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
//                // do stuff with the bitmap
//                pages.add(PageBean(mBitmap, i, pageCount))
//                bitmaps.add(mBitmap)
//                // close the page
//                page.close()
//            }
//        } catch (e: IOException) {
//            e.printStackTrace()
//        } finally {
//            // close the renderer
//            renderer?.close()
//        }
//    }


    private suspend fun readPdf(): List<Bitmap> =
        withContext(Dispatchers.IO) {
            val bitmaps = mutableListOf<Bitmap>()
            var renderer: PdfRenderer? = null
            try {
                val mFileDescriptor = assets.openFd("sample.pdf").parcelFileDescriptor
                renderer = PdfRenderer(mFileDescriptor)
                val pageCount = renderer.pageCount
                for (i in 0 until pageCount) {
                    val page: PdfRenderer.Page = renderer.openPage(i)
                    val width = page.width * 2
                    val height = page.height * 2
                    val mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
                    val canvas = Canvas(mBitmap)
                    canvas.drawColor(Color.WHITE)
                    val paint = Paint()
                    paint.color = Color.BLACK
                    canvas.drawBitmap(mBitmap, 0f, 0f, paint)
                    val r = Rect(0, 0, width, height)
                    val transform = Matrix()
                    transform.setScale(2f, 2f)
                    page.render(mBitmap, r, transform, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
                    pages.add(PageBean(mBitmap, i, pageCount))
                    bitmaps.add(mBitmap)
                    page.close()
                }
            } catch (e: Exception) {
                e.printStackTrace()
//                "文件解析错误".middleToast()
//                file.delete()
            } finally {
                renderer?.close()
            }
            bitmaps
        }

    private suspend fun appendBitmap(
        bitmaps: List<Bitmap>,
        bgColor: Int = Color.WHITE,
        spaceColor: Int = Color.GRAY,
        space: Float = 10f
    ): Bitmap? = withContext(Dispatchers.IO) {
        if (bitmaps.isNullOrEmpty()) return@withContext null
        var width = 0
        var height = 0
        for (i in bitmaps.indices) {
            if (width < bitmaps[i].width) {
                width = bitmaps[i].width
            }
            height += bitmaps[i].height + space.toInt()
        }
        height -= space.toInt()
        val result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
        val canvas = Canvas(result)
        canvas.drawColor(bgColor)
        val paint = Paint()
        paint.isDither = true
        paint.color = spaceColor
        paint.strokeWidth = space
        var top = 0f
        for (j in bitmaps.indices) {
            canvas.drawBitmap(bitmaps[j], 0f, top, paint)
            top += bitmaps[j].height
            if (j < bitmaps.size - 2) {
                canvas.drawLine(0f, top, width.toFloat(), top, paint)
                top += space
            }
            bitmaps[j].recycle()
        }
        result
    }
}

data class PageBean(var bitmap: Bitmap, val index: Int, val count: Int) : IData {
    @SuppressLint("SetTextI18n")
    override fun bind(holder: RecyclerView.ViewHolder) {
        val itemPdfBinding = ItemPdfBinding.bind(holder.itemView)
        itemPdfBinding.pageContent.setImageBitmap(bitmap)
        itemPdfBinding.pageNum.text = "${index + 1}/$count"
    }

}